<?php
include_once($_SERVER["DOCUMENT_ROOT"] . "/model/base_function.php");

function model_add_type($type)
{
	$connection = connect_to_database();

	$query_string = sprintf
	(
	"INSERT INTO type
		SET
			name = \"%s\",
			parent_id = (SELECT * FROM (SELECT id FROM type where name=\"%s\") as tmp);",
	$type["name"],
	$type["parent_type"]
	);
	$result = mysql_query($query_string, $connection);
	if ($result == FALSE)
	{
		print(mysql_error());
		mysql_close($connection);
		return false;
	}

	mysql_close($connection);
	return true;
}

function model_delete_type($id)
{
	$connection = connect_to_database();

	// 将所有标记为这个类型的产品修改为无分类
	$query_string = sprintf
	(
	"UPDATE product
		SET
			type_id = NULL
		WHERE
			type_id = %d",
	$id
	);
	$result = mysql_query($query_string, $connection);
	if ($result == FALSE)
	{
		mysql_close($connection);
		return false;
	}

	// 删除type
	$query_string = sprintf("delete from type where id = %d;", $id);
	$result = mysql_query($query_string, $connection);
	if ($result == FALSE)
	{
		mysql_close($connection);
		return false;
	}

	mysql_close($connection);
	return true;
}

function model_update_type($id, $type)
{
	$connection = connect_to_database();

	$query_string = sprintf
	(
	"UPDATE type
		SET
			name = \"%s\"
		WHERE
			id = %d",
	$type["name"],
	$id
	);
	$result = mysql_query($query_string, $connection);
	if ($result == FALSE)
	{
		print(mysql_error());
		mysql_close($connection);
		return false;
	}

	mysql_close($connection);
	return true;
}

function get_type_list($parent_type)
{
	$type_list = array();

	$connection = connect_to_database();

	$query_string = sprintf("select * from type where parent_id = (select id from type where name = '%s');", $parent_type);
	$result = mysql_query($query_string, $connection);
	if ($result == NULL)
	{
		mysql_close($connection);
		return $type_list;
	}

	while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
	{
		$type = $row;
		$type_list[] = $type;
	}
	
	mysql_close($connection);
	return $type_list;
}

function model_get_news_type_list()
{
	return get_type_list("news");
}

function model_get_product_type_list()
{
	return get_type_list("product");
}
?>
